/*
 * Bunisoft the Open Source Communications Company
 * Copyright 2006, Bunisoft Inc.,
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.teremail.panto;

import java.io.UnsupportedEncodingException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * The content type of the body part, also known as the mime type.  It extends
 * te basic ContentHeader to provide easy access to content type specific
 * properties.  The default is <code>text/plain; charset=us-ascii</code>.
 * 
 * @author Michael Barker
 *
 */
public class ContentType extends ContentHeader {
    
    private final static Map<String, String> DEFAULT_PARAMETERS;
    private final static ContentHeaderFactory<ContentType> FACTORY = 
        new ContentHeaderFactory<ContentType>() {
        
        public ContentType create(String text, String type, String subType, 
                Map<String,String> parameters) {
            return new ContentType(text, type, subType, parameters);
        }
    };
    
    static {
        Map<String, String> tmp = new HashMap<String, String>();
        tmp.put("charset", "us-ascii");
        DEFAULT_PARAMETERS = Collections.unmodifiableMap(tmp);
    }
    
    public ContentType(String text, String type, String subType,
            Map<String, String> parameters) {
        super(text, type, subType, parameters);
    }

    public ContentType() {
        this("text", "plain");
    }
    
    public ContentType(String type, String subType) {
        this(null, type, subType, new HashMap<String, String>());
    }
    
    private final static Pattern PATTERN = Pattern
            .compile("Content-Type:(.*)", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);

    public static ContentType parse(String line) throws ParseException {
        return create(line, PATTERN, FACTORY);
    }
    
    public final static ContentType DEFAULT = new ContentType();
    public final static ContentType DIGEST_DEFAULT = 
        new ContentType("message", "rfc822");

    /**
     * Determine if this body part is a multipart.
     * 
     * @return true if this body part is mulitpart.
     */
    public boolean isMulitpart() {
        return getType().toLowerCase().equals("multipart")
            && getBoundary() != null;
    }
    
    /**
     * Determine if ths body part is a message.
     * 
     * @return true if this body part is a message.
     */
    public boolean isMessage() {
        return getType().toLowerCase().equals("message");
    }
    
    /**
     * Get the mime boundary for this body part, this will be null if
     * <code>isMultipart</code> returns <code>false</code>
     * @return The boundary as a string.
     */
    public String getBoundary() {
        return getParameter("boundary");
    }
    
    /**
     * Get the boundary as a byte array, will be decoded in the US-ASCII charset.
     * 
     * @param includeNL If the boundary should have a &lt;CR&gt;&lt;LF&gt; at
     * the end.
     * @return The boundary as a byte array.
     * @throws UnsupportedEncodingException
     */
    public byte[] getPattern(boolean includeNL) throws UnsupportedEncodingException {
        String boundary = getBoundary();
        if (boundary != null) {
            if (includeNL) {
                return ("\r\n--" + boundary).getBytes("US-ASCII");                
            }
            return ("--" + boundary).getBytes("US-ASCII");
        }
        return null;
    }
    
    /**
     * Returns the default content type for child parts.
     * 
     * @return
     */
    public ContentType getDefault() {
        if ("multipart".equals(getType()) && "digest".equals(getSubType())) {
            return DIGEST_DEFAULT;
        } else {
            return DEFAULT;
        }
    }
    
    /**
     * Returns the subtype, if null it will be set to rfc822 if this is a message
     * or plain for anything else.
     * 
     */
    @Override
    public String getSubType() {
        String subType = super.getSubType();
        if (subType == null) {
            String type = getType();
            if ("message".equals(type)) {
                subType = "rfc822";
            } else {
                subType = "plain";
            }
        }
        return subType;
    }
    
    @Override
    public String getName() {
        return "Content-Type";
    }
    
    @Override
    public String getDefaultParameter(String key) {
        return DEFAULT_PARAMETERS.get(key.toLowerCase());
    }

}